package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Department;
import cn.wolfcode.mapper.DepartmentMapper;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.queryObject;
import cn.wolfcode.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class DepartmentServiceImpl implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    public void delete(Long id) {
        departmentMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Department department) {
        departmentMapper.insert(department);
    }

    @Override
    @Transactional(readOnly = true)
    public Department get(Long id) {
        return departmentMapper.selectByPrimaryKey(id);

    }

    @Override
    @Transactional(readOnly = true)
    public List<Department> listAll() {
        return departmentMapper.selectAll();
    }

    @Override
    public void update(Department department) {
     departmentMapper.updateByPrimaryKey(department);
    }

    @Override
    public PageResult query(queryObject qo) {
        int totalCount = departmentMapper.selectForCount(qo);

        int totalPage = totalCount % qo.getPageSize() == 0 ?
                totalCount / qo.getPageSize() : totalCount / qo.getPageSize()+1;

        if(qo.getCurrentPage()>totalPage){
            qo.setCurrentPage(totalPage);
        }

        if(totalCount==0){
            return new PageResult<>(qo.getCurrentPage(),qo.getPageSize(),totalCount, Collections.emptyList());
        }

        List<Department> listData = departmentMapper.selectForList(qo);
        return new PageResult<>(qo.getCurrentPage(),qo.getPageSize(),totalCount,listData);
    }
}
